﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using DTcms.Web.Libs.Baidu;
using Newtonsoft.Json;

namespace DTcms.Web.WxSdjs
{
    /// <summary>
    /// AddressHandler 的摘要说明
    /// </summary>
    public class AddressHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string query = context.Request["query"];
            if (query == null)
                query = string.Empty;

            string url = "http://api.map.baidu.com/place/v2/suggestion?query=" + query + "&region=郑州市&city_limit=true&output=json&ak=" + AKSNCaculater.Ak;

            List<LbsAddress> addresses = new List<LbsAddress>();
            HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();　　//获取响应，即发送请求
            Stream responseStream = response.GetResponseStream();
            using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8))
            {
                string html = streamReader.ReadToEnd();
                LbsResult lbsResult = JsonConvert.DeserializeObject<LbsResult>(html);
                if (lbsResult.status == 0 && lbsResult.result != null)
                {
                    addresses = lbsResult.result;
                }
            }
            //  排除没有经纬度的地址
            addresses = addresses.Where(a => a.location != null).ToList();
            context.Response.Write(JsonConvert.SerializeObject(addresses));
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }


        public class LbsResult
        {
            public int status { get; set; }
            public string message { get; set; }
            public List<LbsAddress> result { get; set; }
        }
        public class LbsAddress
        {
            public string name { get; set; }
            public string city { get; set; }
            public string district { get; set; }
            public LbsLocation location { get; set; }
        }

        public class LbsLocation
        {
            public decimal lat { get; set; }
            public decimal lng { get; set; }
        }
    }
}